var util = require('../utils/util.js')
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    groupid: {
      type: Number,
      value: 0,
      observer: function(newVal, oldVal) {
        if (newVal > 0) {
          this.loadData();
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    barWidth:100,
    showBar: false,
    isAdmin: false,
    showOrder: false,
    firstShow:true,
    groupInfo: {} //{orderList:[],goodsList:[]}
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function() {
      if (this.data.firstShow){
        this.setData({ "firstShow": false });
      }else{
        this.loadData();
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    previewImage: function(e) {
      var key = e.currentTarget.dataset.ikey;
      var urlList = [];
      if (key == -1) {
        urlList[0] = this.data.groupInfo.headImg;
      } else {
        urlList[0] = this.data.groupInfo.goodsList[key].headImg;
      }
      wx.previewImage({
        current: e.currentTarget.id, // 当前显示图片的http链接
        urls: urlList // 需要预览的图片http链接列表
      })
    },
    viewOrderLog: function(e) {
      //不管理员点击订单
      if (app.globalData.userData.merchantId != this.data.groupInfo.merchantId) {
        return;
      }
      var orderId = e.currentTarget.dataset.orderid;
      var username = e.currentTarget.dataset.username;
      util.gets({
        uri: '/group/order/orderLogDesc/' + orderId,
        success: function(r) {
          if (r.list.length > 0) {
            var content = "";
            for (var i = 0; i < r.list.length; i++) {
              content += r.list[i] + "\r\n";
            }
            if (content){
              wx.showModal({
                title: '“'+username+'”的订单处理',
                content: content,
                showCancel: false
              });
            }
          }
        }
      });
    },
    viewStatus: function(e) {
      var orderId = e.currentTarget.dataset.orderid;
      var status = e.currentTarget.dataset.orderstatus;
      var idx = e.currentTarget.dataset.idx;
      //点击的不是自己的订单，并且不管理员点击订单
      if (this.data.groupInfo.orderList[idx].buyUserId != app.globalData.userData.userId &&
        app.globalData.userData.merchantId != this.data.groupInfo.merchantId) {
        return;
      }
      var that = this;
      //团购管理员
      if (app.getMerchantId() == this.data.groupInfo.merchantId) {
        //付款成功、待发货::做发货成功处理
        if (status == "0") {
          wx.showActionSheet({
            itemList: ['发货成功'],
            success: function(res) {
              if (!res.cancel) {
                that.updateOrderStatus("确定该笔采购已发货？", orderId, idx, "2");
              }
            }
          });
          return;
        }
        //待付款::付款成功、或取消处理
        else if (status == "1") {
          wx.showActionSheet({
            itemList: ['收到货款', '取消采购'],
            success: function(res) {
              if (!res.cancel) {
                if (res.tapIndex == 0) {
                  that.updateOrderStatus("确定已收到该笔采购的货款？", orderId, idx, "0");
                } else if (res.tapIndex == 1) {
                  that.updateOrderStatus("确定取消该笔采购？", orderId, idx, "3");
                }
              }
            }
          });
          return;
        }
      }
      var msg = "";
      switch (status) {
        case "0":
          msg = "等待收货";
          break;
        case "1":
          msg = "等待付款";
          break;
        case "2":
          msg = "采购完成";
          break;
        case "3":
          msg = "采购取消";
          break;
      }
      wx.showToast({
        title: msg,
        icon: 'success',
        duration: 2000
      })
    },
    updateOrderStatus: function(msg, orderId, idx, newStatus) {
      var that = this;
      wx.showModal({
        title: '操作提示',
        content: msg,
        success(res) {
          if (res.confirm) {
            that.sendUpdateStatus(orderId, idx, newStatus);
          }
        }
      })
    },
    sendUpdateStatus: function(orderId, idx, newStatus) {
      var that = this;
      var param = {
        "orderId": orderId,
        "newStatus": newStatus
      };
      util.post({
        uri: '/group/order/updateStatus',
        params: param,
        success: function(r) {
          var rd = {};
          //状态该为已支付（待发货）
          if (newStatus == "0") {
            var orderInfo = that.data.groupInfo.orderList[idx];
            var orderItemList = orderInfo.orderItemList;
            for (var i = 0; i < orderItemList.length; i++) {
              for (var j = 0; j < that.data.groupInfo.goodsList.length; j++) {
                var goods = that.data.groupInfo.goodsList[j];
                if (orderItemList[i].goodsId == goods.goodsId) {
                  var oldAmount=0;
                  if (goods.saleNum){
                    oldAmount = parseInt(goods.saleNum);
                  }
                  var amount = oldAmount + parseInt(orderItemList[i].buyNum);
                  rd["groupInfo.goodsList[" + j + "].saleNum"] = amount;
                }
              }
            }
          }

          rd["groupInfo.orderList[" + idx + "].status"] = newStatus;
          that.setData(rd);
        }
      });
    },
    /**
     * 修改订单
     */
    reserveGoods: function(e) {
      this.toReserve();
    },
    /**
     * 到预购商品页
     */
    toReserve: function(orderIndex) {
      var groupInfo = this.data.groupInfo;
      if(groupInfo.status!='0'){
        wx.showModal({
          content: '已经过期，不能预订',
          showCancel: false,
        })
        return;
      }
      //团购数据
      var group = {
        groupId: groupInfo.groupId,
        merchantId: groupInfo.merchantId,
        name: groupInfo.name
      };
      //商品列表
      var goodsList = [];
      for (var i = 0; i < groupInfo.goodsList.length; i++) {
        var goods = groupInfo.goodsList[i];
        goodsList[i] = {
          goodsId: goods.goodsId,
          name: goods.name,
          price: goods.price,
          unit: goods.unit
        };
      }
      //购买者已经下的订单
      var myOrder = {};
      if (orderIndex) {
        var myOrder = this.data.groupInfo.orderList[orderIndex];
      }

      wx.navigateTo({
        url: "/pages/group/reserve?group=" + JSON.stringify(group) + "&goodsList=" + JSON.stringify(goodsList) + "&orderInfo=" + JSON.stringify(myOrder),
        fail: function(e) {
          console.log(e);
        }
      })
    },
    updateGroup: function(e) {
      var groupId = e.currentTarget.dataset.groupid;
      wx.navigateTo({
        url: '/pages/group/group-edit?groupId=' + groupId,
        fail: function(e) {
          console.log(e);
        }
      })
    },
    loadData: function() {
      if (this.data.groupid == 0) {
        return;
      }
      var that = this;

      util.gets({
        uri: '/group/group/info/' + this.data.groupid,
        success: function(r) {
          var b = app.globalData.userData.merchantId == r.group.solitaire.merchantId;
          var sorder = r.group.orderList.length > 0;
          that.setData({
            "groupInfo": r.group,
            "showOrder": sorder,
            "isAdmin": b
          });
        }
      });
    },
    toPage:function(optins){
      var k = optins.currentTarget.dataset.key;
      var toUrl;
      switch(k){
        case "1":
          toUrl ="/pages/index/index";
          break;
        case "2":
          toUrl = "/pages/group/group-list";
          break;
        case "3":
          toUrl = "/pages/my/home";
          break;
      }
      wx.switchTab({
        url: toUrl,
      })
    },
    showLocation:function(){
      var location = this.data.groupInfo.location;
      wx.openLocation({
        latitude: location.latitude,
        longitude: location.longitude,
        scale: 18
      })
    }
  }
})